package com.kerrykidz.workflow.service.impl;

import java.util.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kerrykidz.common.PrimaryKeyGenerator;
import com.kerrykidz.common.PrimaryKeyGenerator.BusinessType;
import com.kerrykidz.system.service.IUserService;
import com.kerrykidz.system.util.ConstantUtil;
import com.kerrykidz.system.util.DataSourceUtil;
import com.kerrykidz.system.util.DateUtil;
import com.kerrykidz.system.vo.UserInfo;
import com.kerrykidz.workflow.dao.mapper.GblHrmCLvetypeEntityMapper;
import com.kerrykidz.workflow.dao.mapper.HrmLeaveEntityMapper;
import com.kerrykidz.workflow.dao.model.GblHrmCLvetypeEntity;
import com.kerrykidz.workflow.dao.model.HrmLeaveEntity;
import com.kerrykidz.workflow.service.ILeaveWorkflowService;
import com.kerrykidz.workflow.service.IWorkflowService;
import com.kerrykidz.workflow.vo.TypeVo;
import com.kerrykidz.workflow.vo.LeaveVo;
import com.kerrykidz.workflow.vo.SearchParamVo;
import com.kerrykidz.workflow.vo.WorkflowParamVo;
import com.kerrykidz.workflow.vo.WorkflowVo;
import com.rdp.framework.exception.RDPException;
import com.rdp.util.lang.StringUtil;

/**
 * 请假流程接口实现类
 * @author zhuss
 *
 */
@Service
public class LeaveWorkflowServiceImpl implements ILeaveWorkflowService{

	@Autowired
	GblHrmCLvetypeEntityMapper gblHrmCLvetypeEntityMapper;
	
	@Autowired
	HrmLeaveEntityMapper hrmLeaveEntityMapper;
	
	@Autowired
	IUserService userService;
	
	@Autowired
	IWorkflowService workflowService;
	
	@Autowired
	DataSourceUtil das;
	
	
	/**
	 * 获取所有的请假类型
	 */
	@Override
	public List<TypeVo> findLeaveTypeList() throws RDPException{
		List<GblHrmCLvetypeEntity> list = gblHrmCLvetypeEntityMapper.findTypeList();
		List<TypeVo> volist = new ArrayList<TypeVo>();
		if(list.size() != 0 && list != null){
			for(GblHrmCLvetypeEntity glce :list){
				volist.add(glce.changeVo());
			}	
			return volist;
		}
		return null;
	}

	/**
	 * 查询请假列表
	 */
	@Override
	public List<LeaveVo> findLeaveList(SearchParamVo searchParam) throws RDPException{
		searchParam.setIspaging(true);
		List<LeaveVo> list = new ArrayList<LeaveVo>();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId", searchParam.getUserInfo().getUserId());
		map.put("applyName", searchParam.getApplyName());
		map.put("leaveType", searchParam.getType());
		if(StringUtils.isNotBlank(searchParam.getStartTime()))
			map.put("lveStart", DateUtil.getDate(searchParam.getStartTime()+" 00:00:00", "yyyy/MM/dd HH:mm:ss"));
		else
			map.put("lveStart",null);
		if(StringUtils.isNotBlank(searchParam.getEndTime()))
			map.put("lveEnd", DateUtil.getDate(searchParam.getEndTime()+" 23:59:59", "yyyy/MM/dd HH:mm:ss"));
		else
			map.put("lveEnd",null);
		searchParam.setParams(map);
		List<HrmLeaveEntity> hlelist = hrmLeaveEntityMapper.findLeaveList(searchParam);
		for(HrmLeaveEntity hl : hlelist){
			LeaveVo vo = hl.changeLeaveVo();
			vo.setWorkflowVo(workflowService.getWorkflowVo(hl.getFkFlowinstId(), hl.getStatus(), searchParam.getUserInfo()));
			list.add(vo);
		}
		return list;
	}

	/**
	 * 保存请假流程
	 * @throws RDPException 
	 */
	@Override
	@Transactional
	public void saveLeave(HrmLeaveEntity hle,String btnType,UserInfo user) throws RDPException {
		hle.setPkLeaveId(PrimaryKeyGenerator.getPrimaryKey(BusinessType.QJ, user.getAbbrCode()));
		hle.setStatus("1");
		hle.setApplyBy(user.getUserId());
		hle.setFkBranId(user.getBranId());
		hle.setLveStart(DateUtil.getDate(hle.getLveStartYMD()+" "+hle.getLveStartHM(),"yyyy/MM/dd HH:mm"));
		hle.setLveEnd(DateUtil.getDate(hle.getLveEndYMD()+" "+hle.getLveEndHM(),"yyyy/MM/dd HH:mm"));
		hle.setModiBy(user.getUserId());
		hrmLeaveEntityMapper.saveEntity(hle);
		if(btnType.equals("2")){//如果是提交按钮启动流程
			if(user.getRoleList().size() != 0){
				if(!user.getRoleList().contains("102")){
					String procId = workflowService.startWorkflow("leave",hle.getPkLeaveId(),user);
					if(StringUtil.isNotBlank(procId)){
						HrmLeaveEntity hl = new HrmLeaveEntity();
						hl.setPkLeaveId(hle.getPkLeaveId());
						hl.setFkFlowinstId(procId);
						hl.setStatus("2");
						hl.setModiTime(new Date());
						hrmLeaveEntityMapper.updateEntity(hl);
						//判断是否是门店
						if(StringUtil.isNotBlank(user.getBranId())){
							//如果是门店的话就进行数据上传
							if(user.getBranId().indexOf("ZB") == -1){
								HrmLeaveEntity h = hrmLeaveEntityMapper.findEntityById(hle.getPkLeaveId());
								das.executeLeave(h,"insert");
							}
						}
					}
				}
			}
		} 
	}
	
	/**
	 * 根据ID获取请假
	 * @return
	 * @throws RDPException 
	 */
	public LeaveVo findLeaveById(String id,UserInfo user) throws RDPException{
		HrmLeaveEntity hle = hrmLeaveEntityMapper.findEntityById(id);
		LeaveVo vo = new LeaveVo();
		if(null != hle){
			vo = hle.changeLeaveVo();
			WorkflowVo wv = workflowService.getWorkflowVo(hle.getFkFlowinstId(), hle.getStatus(), user);
			wv.setOptHisVoList(workflowService.findOpinions(hle.getFkFlowinstId(),user));
			vo.setWorkflowVo(wv);
		}
		return vo;
	}

	
	/**
	 * 修改请假
	 */
	@Transactional
	public void updateLeave(HrmLeaveEntity hle,String btnType,UserInfo user)throws RDPException{
		hle.setModiBy(user.getUserId());
		if(StringUtils.isNotBlank(hle.getLveStartYMD())&&StringUtils.isNotBlank(hle.getLveStartHM()))
			hle.setLveStart(DateUtil.getDate(hle.getLveStartYMD()+" "+hle.getLveStartHM(),"yyyy/MM/dd HH:mm"));
		if(StringUtils.isNotBlank(hle.getLveEndYMD())&&StringUtils.isNotBlank(hle.getLveEndHM()))
			hle.setLveEnd(DateUtil.getDate(hle.getLveEndYMD()+" "+hle.getLveEndHM(),"yyyy/MM/dd HH:mm"));
		hrmLeaveEntityMapper.updateEntity(hle);
		if(btnType.equals("2")){//如果是提交按钮启动流程
			if(user.getRoleList().size() != 0){
				if(!user.getRoleList().contains("102")){
					
						String procId = workflowService.startWorkflow("leave",hle.getPkLeaveId(),user);
						if(StringUtil.isNotBlank(procId)){
							hle.setFkFlowinstId(procId);
							hle.setStatus("2");
							hle.setModiTime(new Date());
							hrmLeaveEntityMapper.updateEntity(hle);
							//判断是否是门店
							if(StringUtil.isNotBlank(user.getBranId())){
								//如果是门店的话就进行数据上传
								if(user.getBranId().indexOf("ZB") == -1){
									HrmLeaveEntity h = hrmLeaveEntityMapper.findEntityById(hle.getPkLeaveId());
									das.executeLeave(h,"insert");
								}
							}
					}
				}
			}
		}else if(btnType.equals("3") || btnType.equals("4")){
			WorkflowParamVo workflowparam = new WorkflowParamVo();
			workflowparam.setProcessInstanceId(hle.getFkFlowinstId());
			workflowparam.setBusinessKey(hle.getPkLeaveId());
			workflowparam.setUserInfo(user);
			//判断是否是门店
			if(StringUtil.isNotBlank(user.getBranId())){
				if(btnType.equals("3")){//如果是重新申请
					int rel = 1;
					//判断是否是门店
					if(StringUtil.isNotBlank(user.getBranId())){
						//如果是门店的话就进行数据上传
						if(user.getBranId().indexOf("ZB") == -1){
							HrmLeaveEntity h = hrmLeaveEntityMapper.findEntityById(hle.getPkLeaveId());
							rel = das.executeLeave(h,"update");
						}
					}
					if(rel>0){
						workflowparam.setHandleAdviceDes(ConstantUtil.WORKFLOW_STATUS_REAPPLY);
						workflowparam.setHandleResult("3");//重新申请
						completeLeave(workflowparam);
					}
				}
				if(btnType.equals("4")){//结束流程
					workflowparam.setHandleResult("4");//结束流程
					completeLeave(workflowparam);
				}
			}
		}else if(btnType.equals("5") ){ //在草稿状态的时候删除
			hle.setStatus("0");
			hrmLeaveEntityMapper.updateEntity(hle);
		}
	}

	/**
	 * 处理任务
	 */
	@Transactional
	@Override
	public void completeLeave(WorkflowParamVo workflowparam) throws RDPException {
		HrmLeaveEntity hl = new HrmLeaveEntity();
		hl.setPkLeaveId(workflowparam.getBusinessKey());
		hl.setStatus("2");
		if(StringUtils.isNotBlank(workflowparam.getHandleResult())){
			if(workflowparam.getHandleResult().equals("1") || workflowparam.getHandleResult().equals("3")){//递交或重新申请
				if(workflowparam.getHandleResult().equals("1"))
					workflowparam.setHandleAdviceDes(workflowparam.getHandleAdvice().equals("1")?"同意":"不同意");
				ProcessInstance pi = workflowService.complete(workflowparam);
				//如果已经完成了，修改流程状态
				if(pi == null){
					if(workflowparam.getHandleAdvice().equals("1")){//审批同意
						hl.setStatus("3");
					}else
						hl.setStatus("4");
				}
			}else if(workflowparam.getHandleResult().equals("2")){//退单
				hl.setStatus("2");
				workflowService.backProcessToStart(workflowparam);
			}else if(workflowparam.getHandleResult().equals("4")){//结束申请
				hl.setStatus("5");
				workflowService.deleteProcessInstance(workflowparam);
			}
		}
		hrmLeaveEntityMapper.updateEntity(hl);
	}

}
